<?php
/**
 * 邮件分组控制器类
 * Created by PhpStorm.
 * User: Liujianlin
 * Date: 2017/6/5
 * Time: 16:29
 */

namespace app\controllers\crontab;


use yii;
use app\models\marketing\MailGroup;
use app\models\marketing\MailSubgroup;
use app\models\marketing\MailSendlist;
use app\components\TemplateMarket;
use yii\data\Pagination;
use app\components\smarty\SmartyNewRenderer;
use app\components\EmailMarket;
use app\models\marketing\MailGroupEmailTypeStatistics;
use app\components\Site;
class SyncDataController extends \app\base\Controller
{
   
    /**
     * 为了兼容以前的接口数据，旧的一些数据先在这里做成配置
     */
    protected $syncDataConfig = [
        'gamiss' => [
            'cart' => [ // 购物车邮件
                'sys_time' => 61200,
                'sys_type' => 1,  // 同步数据类型 1 coupon码，2 cookie码
                'add_cart_day' => 3,
            ],
        ],
         'twinkledeals' => [
            'cart' => [ // 购物车邮件
                'sys_time' => 8*3600,
                'sys_type' => 2,  // 同步数据类型 1 coupon码，2 cookie码
            ],
        ],

        'sammydress' => [
            'cart' => [ // 购物车邮件
                'sys_time' => 7*3600,
                'sys_type' => 2,  // 同步数据类型 1 coupon码，2 cookie码
            ],
        ],
        'gearbest' => [
            'cart' => [ // 购物车邮件
                'sys_time' => 9*3600,
                'sys_type' => 3,  // gb的cookie_code有点特殊，单独写成3
            ],
        ],

    ];
    
    protected $couponCodeApi = [
        'gamiss' => [
            'dev'=>'http://gamiss.com.trunk.s1.egomsl.com/syn/syn_edm_coupon.php',
            'test'=>'http://gamiss.com.trunk.s1.egomsl.com/syn/syn_edm_coupon.php',
            'product'=>'http://www.gamiss.com/syn/syn_edm_coupon.php',
        ]
    ];
     protected $cookieCodeApi = [
        'twinkledeals' => [
            'dev'=>'http://twinkledeals.com.trunk.s1.egomsl.com/eload_admin/crontab/email_only_success_goods.php',
            'test'=>'http://twinkledeals.com.trunk.s1.egomsl.com/eload_admin/crontab/email_only_success_goods.php',
            'product'=>'http://www.twinkledeals.com/eload_admin/crontab/email_only_success_goods.php',

        ],
        
        'gearbest' => [
            'dev'=>'http://www.gearbest.com.b.s1.egomsl.com/eload_admin/crontab/email_only_success_goods.php',
            'test'=>'http://www.gearbest.com.b.s1.egomsl.com/eload_admin/crontab/email_only_success_goods.php',
            'product'=>'http://admin.gearbest.com/eload_admin/crontab/email_only_success_goods.php',
        ],
         
        'sammydress' => [
            'dev'=>'http://www.sammydress.com.b.s1.egomsl.com/eload_admin/crontab/email_only_success_goods.php',
            'test'=>'http://www.sammydress.com.b.s1.egomsl.com/eload_admin/crontab/email_only_success_goods.php',
            'product'=>'http://www.sammydress.com/eload_admin/crontab/email_only_success_goods.php',
        ], 

    ];
    /**
     * 更新邮件专享价cookie
     */
    public function postCartInfo($data,$apiUrl) 
    {    
        $token = 'c346eb79b0b21b26a9fMFj8M7xPMoO0O';

        $postData = "keys_code={$token}&data=".serialize($data);//$_CFG['keys_code'] 为内部验证码

        $return_data = $this->curlPost($apiUrl, $postData);

        return $return_data;
    }

    /**
     * post 数据到指定URL
     * $post eg : "a=1&c=yy"
     */
    public function curlPost($url,$post){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    
    /**
     * 同步coupon码
     */
    public function syncCoupon($webName,$mailType) {
        $tableName = "user_{$webName}_goods_data";
        
        $daysAgo =  date("Y-m-d",strtotime((1-$this->syncDataConfig[$webName][$mailType]['add_cart_day']).' day'));
        $stime = strtotime($daysAgo." 00:00:00");
        $etime = strtotime($daysAgo." 23:59:59");
        $curBjTime = \yii::$app->bjTime->time();
        $sql = "select coupon_code from {$tableName} where add_cart_time >= $stime AND add_cart_time <= $etime AND coupon_code !='' AND synchro = 0 GROUP BY coupon_code ";
        
        
        $arr = yii::$app->db->createCommand($sql)->queryAll();
        if ( !empty($arr) ) {
            $data = array();
            $startTime = time();
            $endTime = $startTime + 48*3600;
            
            foreach ($arr as $key => $val ) {
                $data['coupon'] = $arr[$key]['coupon_code'];
                $data['exp_time'] = $endTime;
                $apiUrl = $this->couponCodeApi[$webName][YII_ENV];
                $result = $this->postCartInfo($data,$apiUrl);
                if (strpos( $result , 'success') !== 'false') {
                    $updateSql = "UPDATE {$tableName} SET synchro = 1 WHERE  add_cart_time >= $stime AND add_cart_time <= $etime AND coupon_code = '{$data['coupon']}' ";
                    $re = yii::$app->db->createCommand($updateSql)->execute();
                    if ( $re ) {
                        echo "COUPON_CODE同步成功<br>";
                    }
                } else {
                    echo "COUPON_CODE同步失败<br>";
                }
            } 
        } else {
            echo "COUPON_CODE已经同步完毕<br>";
        }
    }
    
    /**
     * 同步动态cookie_code 
     */ 
    public function syncCookieIndefinite($webName,$mailType)
    {
        $tableName = "user_{$webName}_goods_data";
        $sql = "select * from {$tableName} where is_set_goods_cookie_code=1 and synchro = 0 limit 500";
        $arr = yii::$app->db->createCommand($sql)->queryAll();
        if ( !empty($arr) ) {
            $data = $goods_ids = array();
            $startTime = time();
            $endTime = $startTime + 48*3600;
            foreach ($arr as $key=>$val) {
                $goods_ids[] = $val['id'];
                $goodsList = unserialize($val['goods_list']);
                if (!empty($goodsList) && is_array($goodsList)) {
                    foreach ($goodsList as $goodsCur) {
                        $goodsDataTemp = [];
                        $goodsDataTemp['goods_sn'] = $goodsCur['goods_sn'];
                        $goodsDataTemp['goods_id'] = $goodsCur['goods_id'];
                        $goodsDataTemp['cookie_code'] = $goodsCur['cookie_code'];
                        $goodsDataTemp['start_time'] = $startTime;
                        $goodsDataTemp['end_time'] = $endTime;
                        $goodsDataTemp['email_only'] = $goodsCur['goods_sn']."_edm";
                        $goodsDataTemp['wid'] = isset($goodsCur['wid'])?$goodsCur['wid']:'';
                        $goodsDataTemp['rec_id'] = $goodsCur['rec_id']; 
                        $data[] = $goodsDataTemp;
                    }
                }
            }
            $apiUrl = $this->cookieCodeApi[$webName][YII_ENV];
            $result = $this->postCartInfo($data,$apiUrl);
            
            
            $result = unserialize($result);
            
            
            if ($goods_ids) {
                $goods_id_str = implode(',',$goods_ids);
            } else {
                $goods_id_str = '0';
            }
            
            if (!empty($result['status']) && $result['status'] == 1) {
                if ( !empty($result['msg']['success']) ) {
                    $updateSql = "UPDATE {$tableName} SET synchro = 1 WHERE id in(".$goods_id_str.")";
                } elseif (!empty($result['msg']['price'])) {
                    $updateSql = "UPDATE {$tableName} SET synchro = 2 WHERE id in(".$goods_id_str.")"; 
                } elseif (!empty($result['msg']['cart'])) {
                    $updateSql = "UPDATE {$tableName} SET synchro = 3 WHERE id in(".$goods_id_str.")"; 
                }
                
                if ($updateSql) {
                    $re = yii::$app->db->createCommand($updateSql)->execute();
                }
            }
            
        } else {
             echo "COUPON_CODE已经同步完毕<br>";
        }
        
    }
     /**
     * 同步coupon码
     */
    public function syncCookie($webName,$mailType) {
        $tableName = "user_{$webName}_goods_data";
        
        $sql = "select * from {$tableName} where cookie_code !='' AND synchro = 0 limit 500";
        
        
        $arr = yii::$app->db->createCommand($sql)->queryAll();
        if ( !empty($arr) ) {
            $data = $goods_ids = array();
            $startTime = time();
            $endTime = $startTime + 48*3600;
            
            foreach ($arr as $key => $val ) {
                $goods_info = json_decode(stripslashes($val['goods_list']),true);
                $data[$key]['goods_sn'] = $goods_info['goods_sn'];
                $data[$key]['goods_id'] = $goods_info['goods_id'];
                $data[$key]['cookie_code'] = $val['cookie_code'];
                $data[$key]['start_time'] = $startTime;
                $data[$key]['end_time'] = $endTime;
                $data[$key]['email_only'] = $goods_info['goods_sn']."_edm";
                $data[$key]['wid'] = isset($goods_info['wid'])?$goods_info['wid']:'';
                $data[$key]['rec_id'] = $goods_info['rec_id']; 
                $goods_ids[] = $val['id'];
            }
                $apiUrl = $this->cookieCodeApi[$webName][YII_ENV];
                $result = $this->postCartInfo($data,$apiUrl);
                $result = unserialize($result);
                $goods_id_str = implode(',',$goods_ids);
                if ( $result['status'] == 1 ) {
                    if ( !empty($result['msg']['success']) ) {
                        $success_cookie_str = "'".implode("','", $result['msg']['success'])."'";
                        $updateSql = "UPDATE {$tableName} SET synchro = 1 WHERE cookie_code in (" .$success_cookie_str . ") and id in(".$goods_id_str.")";
                        $re = yii::$app->db->createCommand($updateSql)->execute();
                        
                    }
                    if ( !empty($result['msg']['price']) ) {
                        $price_cookie_str = "'".implode("','", $result['msg']['price'])."'";
                        $updateSql = "UPDATE {$tableName} SET synchro = 2 WHERE cookie_code in (" .$price_cookie_str . ") and id in(".$goods_id_str.")";
                        $re = yii::$app->db->createCommand($updateSql)->execute();
                    }
                    if ( !empty($result['msg']['cart']) ) {
                        $cart_cookie_str = "'".implode("','", $result['msg']['cart'])."'";
                        $updateSql = "UPDATE {$tableName} SET synchro = 3 WHERE cookie_code in (" .$cart_cookie_str . ") and id in(".$goods_id_str.")";
                        $re = yii::$app->db->createCommand($updateSql)->execute();
                    }

                }
                
            } else {
                echo "COUPON_CODE已经同步完毕<br>";
            }
    }
    /**
     * 同步相关数据到网站端
     */
    public function actionSyncData()
    {
       
        foreach ($this->syncDataConfig as $webName=>$webMailInfo) {
            if ($webMailInfo) {
                $curBjTime = \yii::$app->bjTime->time();
                $curDate = \yii::$app->bjTime->date('Y-m-d');
                $curDayStart = \yii::$app->bjTime->strtotime($curDate." 00:00:00");
                $data['module_name'] = "marketing_email";
                foreach ($webMailInfo as $mailType=>$webMailInfoVal) {
                    if ($curBjTime - $curDayStart >= $webMailInfoVal['sys_time']) {     // 说明已经到了同步数据的时间
                        if ($webMailInfoVal['sys_type'] == 1) { // 说明是coupon码
                            $this->syncCoupon($webName,$mailType);    
                        }
                        else if($webMailInfoVal['sys_type'] == 2)
                        {
                            $this->syncCookie($webName,$mailType); 
                        }
                        else if($webMailInfoVal['sys_type'] == 3) {
                            $this->syncCookieIndefinite($webName,$mailType); 
                        }
                            
                    }
                }
            } 
        }
        
        
    }
}
